
const { app, BrowserView, screen, session } = require('electron');
const path = require('path')

const EnvContext = require('../../../common/context/EnvContext');
const { mainWinConst } = require('../../../common/constans/mainWinConstans')
const eJSONStorage = require('electron-json-storage');



exports.createView = function (window, preloadPath, HtmlPath, pluginId, height, callback) {
    doCreateView(window, preloadPath, HtmlPath, pluginId, height, callback)
}



function doCreateView(window, preloadPath, htmlPath, pluginId, height, callback) {
    if (!window) {
        if (callback) callback()
        return
    }
    // 从缓存中加载view
    // const theView = EnvContext.getInstance().getViewByPluginId(pluginId)
    // if (theView != null) {
    //     console.info("正在重置view", theView.getBounds(), pluginId)
    //     theView.setBounds({ x: 0, y: 0, width: 800, height: 600 });
    //     window.setBrowserView(theView);
    //     if (callback) callback()
    //     return
    // }

    // todo 如果当前已经是初始状态则不再重复执行view创建

    const ses = session.fromPartition("persist:" + pluginId, { cache: true });
    // window.getBrowserViews().map(view => {
    //     window.removeBrowserView(view)
    //     view.webContents.closeDevTools()
    // })


    console.info("preloadPath", preloadPath, htmlPath)

    loadCookieState(pluginId, ses);

    view = new BrowserView({
        webPreferences: {
            enableRemoteModule: false,
            webSecurity: false,
            nodeIntegration: true,
            contextIsolation: true,
            devTools: true,
            webviewTag: true,
            preload: preloadPath,
            session: ses,
        },
    });
    window.setBrowserView(view);
    if (htmlPath.startsWith("http")) {
        view.webContents.loadURL(htmlPath);
    } else[
        view.webContents.loadFile(htmlPath)
    ]


    // 保存view
    EnvContext.getInstance().setViewByPluginId(pluginId, view)

    window.once("ready-to-show", () => {
        view.setBounds({ x: 0, y: 60, width: 800, height: 600 });
        view.setAutoResize({ width: true });
        // window.setSize(800, height ? height : 60);
        // view.webContents.openDevTools({ mode: "detach" });
        // if (renderJs) {
        //     try {

        //         view.webContents.executeJavaScript(renderJs);
        //         console.info("renderJs", renderJs)
        //     } catch (e) { console.error(e) }
        // }
        if (callback) callback()
    });
}



function loadCookieState(pluginId, currentSession) {
    eJSONStorage.get(pluginId, (error, cookieData) => {
        // Check for empty object returned, this means no saved sessions.
        if (Object.entries(cookieData).length === 0) {
            return;
        }
        if (error) {
            throw error;
        }
        // If we have saved sessions and no errors, load the sessions.
        cookieData.forEach(cookie => currentSession.cookies.set(cookie, error => {
            if (error) console.error(error);
        }));
    });
}


function saveCookieState(pluginId, currentSession) {
    currentSession.cookies.get({}, (_, cookies) => {
        cookies.forEach(cookie => {
            // URL is a required paramater, take it from the domain with a little parsing.
            // Twitter always uses HTTPS otherwise, we would need to check for http vs https too.
            const cDomain = !cookie.domain.startsWith('.') ? `.${cookie.domain}` : cookie.domain;
            cookie.url = `https://www${cDomain}`
        });
        // Save the set of cookies against the session name.
        eJSONStorage.set(pluginId, cookies, err => {
            if (err) {
                throw err;
            }
        });
    });
}